<?php

$arr = split('/', getcwd());
$ch = array_chunk($arr, count($arr) - 5);
$path = implode('/', $ch[0]);
$path = $path . '/';
define('DRUPAL_ROOT', $path);
require_once $path . 'includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
require_once "nusoap-0.9.5/lib/nusoap.php";

function get_data() {
//    taxonomy_get_tree(1);
    $out = array();
    $jobs = taxonomy_get_tree(2); //region
    foreach ($jobs as $key => $value) {
        $out['jobs'][$value->tid] = $value->name;
    }
    $regions = taxonomy_get_tree(3); //jobs
    foreach ($regions as $key => $value) {
        $out['regions'][$value->tid] = $value->name;
    }
//    $out = array('regions' => $regions, 'jobs' => $jobs);
    return json_encode($out);
}

function search_worker($job, $region) {
    global $base_url;
    $job_term = array_keys(taxonomy_get_term_by_name($job));
    $job_term = $job_term[0];
    $region_term = array_keys(taxonomy_get_term_by_name($region));
    $region_term = $region_term[0];
    $query = db_select('node', 'n');
    $query->leftjoin('field_data_field_rank', 'r', 'n.nid = r.entity_id');
    $query->fields('n', array('nid'));
    $query->orderBy('r.field_rank_rating', 'DESC');
    $result = $query->execute();
    $workers = array();
    foreach ($result as $n) {
        $node = node_load($n->nid);
        if (isset($node->field_worker_job) && count($node->field_worker_job > 0)) {
            $fjob = false;
            $freg = false;
            if (count($node->field_worker_job) > 0) {
                foreach ($node->field_worker_job['und'] as $job) {
                    if ($job['tid'] == $job_term) {
                        $fjob = true;
                        break;
                    }
                }
            }
            if (isset($node->field_address) && count($node->field_address) > 0) {
                foreach ($node->field_address['und'] as $reg) {
                    if ($reg['tid'] == $region_term) {
                        $freg = true;
                        break;
                    }
                }
            }
            if ($fjob && $freg) {
                $workers[] = array('rank' => $node->field_rank['und'][0]['rating'],
                    'name' => $node->title,
                    'nid' => $node->nid,
                    'email' => $node->field_email['und'][0]['value'],
                    'tel' => $node->field_mobile_num['und'][0]['value'],
                    'ssn' => $node->field_ssn['und'][0]['value'],
                    'url' => $base_url . '/' . drupal_lookup_path('alias', 'node/' . $node->nid)
                );
            }
        }
    }
    return json_encode($workers);
}

function evaluate_worker($code, $rate) {
    $query = db_select('node', 'n');
    $query->condition('n.title', $code);
    $query->condition('n.type', 'request');
    $query->join('field_data_field_requested_worker', 'w', 'n.nid=w.entity_id');
    $query->fields('w', array('field_requested_worker_nid'));
    $query->fields('n', array('nid'));
    $result = $query->execute();
    $worker = NULL;
    $request = NULL;
    foreach ($result as $key => $value) {
        $worker = $value->field_requested_worker_nid;
        $request = $value->nid;
        break;
    }
    if ($worker != NULL && $request != NULL) {
        $w = node_load($worker);
        $r = node_load($request);
        if (count($r->field_state) == 0 || $r->field_state['und'][0]['value'] == 0) {
            if (count($w->field_evaluated_times) == 0) {
                $w->field_rank['und'][0]['rating'] = $rate;
                $w->field_evaluated_times['und'][0]['value'] = 1;
            } else {
                $total_rank = $w->field_rank['und'][0]['rating'];
                $times = $w->field_evaluated_times['und'][0]['value'];
                $w->field_rank['und'][0]['rating'] = ($total_rank + $rate) / ($times + 1);
                $w->field_evaluated_times['und'][0]['value'] = $w->field_evaluated_times['und'][0]['value'] + 1;
            }
            $vote = array();
            $vote['entity_id'] = $w->nid;
            $vote['value'] = ($total_rank + $rate) / ($times + 1);
            votingapi_set_votes($vote);
            $r->field_state['und'][0]['value'] = 1;
            node_save($r);
            node_save($w);
            return 'rated';
        } else {
            return 'rated_before';
        }
    } else {
        return 'error_code';
    }
}

function request_worker($nid, $phone, $email, $interval, $period) {
    $request = new stdClass();
    $request->type = 'request';
    node_object_prepare($request);
    $request->created = time();
    $request->title = createRandomPassword();
    $request->field_requested_worker['und'][0]['nid'] = $nid;
    $request->field_task_period['und'][0]['interval'] = $interval;
    $request->field_task_period['und'][0]['period'] = $period;
    $request->field_client_phone['und'][0]['value'] = $phone;
    $request->field_client_email['und'][0]['email'] = $email;
    node_save($request);
    return $request->title;
}

$server = new soap_server();
$server->configureWSDL("workers", "urn:workers");
$server->register("search_worker", array("job" => "xsd:string", "region" => "xsd:string"), array("return" => "xsd:string"), "urn:workers", "urn:workers#search_worker", "rpc", "encoded", "Get a listing of workers by category.");
$server->register("request_worker", array("nid" => "xsd:string",
    'phone' => "xsd:string",
    "email" => "xsd:string",
    'interval' => "xsd:string",
    'period' => "xsd:string"), array("return" => "xsd:string"), "urn:workers", "urn:workers#request_worker", "rpc", "encoded", "Request specific worker.");
$server->register("get_data", array(), array("return" => "xsd:string"), "urn:workers", "urn:workers#get_data", "rpc", "encoded", "Get a listing jobs and regions");
$server->register("evaluate_worker", array("code" => "xsd:string", "rate" => "xsd:string"), array("return" => "xsd:string"), "urn:workers", "urn:workers#evaluate_worker", "rpc", "encoded", "Evaluate Worker.");
$server->service($HTTP_RAW_POST_DATA);